package com.xnyzc.lhy.mis.service.impl.worksheet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.WorksheetRv;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.exception.WorksheetException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.EDriverComingUserType;
import com.xnyzc.lhy.common.penum.order.*;
import com.xnyzc.lhy.common.penum.worksheet.EWorksheetResource;
import com.xnyzc.lhy.common.penum.worksheet.WorksheetErrorCode;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.mis.entity.cms.OaSysRole;
import com.xnyzc.lhy.mis.entity.area.DidiSysArea;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.driver.wallet.OaDWalletRecord;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.order.OaOrderOtherPrice;
import com.xnyzc.lhy.mis.entity.order.OaServiceOrderOperationRecord;
import com.xnyzc.lhy.mis.entity.param.punishment.OaDUserPenaltyParam;
import com.xnyzc.lhy.mis.entity.param.worksheet.didi.*;
import com.xnyzc.lhy.mis.entity.param.worksheet.softbar.HeliPhoneUrlResult;
import com.xnyzc.lhy.mis.entity.param.worksheet.softbar.SoftPhoneUserInfoResult;
import com.xnyzc.lhy.mis.entity.system.OaSysBillRuleGroup;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.worksheet.OaSysWorksheet;
import com.xnyzc.lhy.mis.entity.worksheet.OtherOpenPidParam;
import com.xnyzc.lhy.mis.entity.worksheet.OtherOpenPidResults;
import com.xnyzc.lhy.mis.feign.didi.CustomerServiceOperationService;
import com.xnyzc.lhy.mis.feign.didi.WorkService;
import com.xnyzc.lhy.mis.mapper.area.DidiSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.cms.OaSysRoleMapper;
import com.xnyzc.lhy.mis.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.mis.mapper.driver.wallet.OaDWalletRecordMapper;
import com.xnyzc.lhy.mis.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.mis.mapper.order.OaOrderOtherPriceMapper;
import com.xnyzc.lhy.mis.mapper.order.OaServiceOrderOperationRecordMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.worksheet.OaSysWorksheetMapper;
import com.xnyzc.lhy.mis.mapper.worksheet.UserInfoMapper;
import com.xnyzc.lhy.mis.service.punishment.IOaDUserPenaltyService;
import com.xnyzc.lhy.mis.service.worksheet.*;
import com.xnyzc.lhy.mis.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.order.entity.param.synchronization.PassengerBill;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.resource.entity.enumall.CustomerTypeEnum;
import com.xnyzc.lhy.resource.entity.worksheet.param.*;
import com.xnyzc.lhy.resource.entity.worksheet.param.heli.FromHeliWorksheetParam;
import com.xnyzc.lhy.resource.entity.worksheet.result.DriverDetailResult;
import com.xnyzc.lhy.resource.entity.worksheet.result.OrderDetailListResult;
import com.xnyzc.lhy.resource.entity.worksheet.result.OrderDetailsResult;
import com.xnyzc.lhy.resource.entity.worksheet.result.OrderStatusResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 工单信息表 服务实现类
 * </p>
 *
 * @author haoyfa
 * @since 2019-11-04
 */
@Slf4j
@Service
public class WorksheetServiceImpl extends ServiceImpl<OaSysWorksheetMapper, OaSysWorksheet> implements IWorksheetService {
    /**
     * 自费叫车Mapper
     */
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IOrderPersonalService iOrderPersonalService;

    @Autowired
    private OaOrderOtherPriceMapper oaOrderOtherPriceMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    CustomerServiceOperationService customerServiceOperationService;

    @Autowired
    IOaSysWorksheetService iOaSysWorksheetService;

    @Autowired
    IOaDUserPenaltyService iOaDUserPenaltyService;

    //didi工单操作服务
    @Autowired
    WorkService workService;

    @Autowired
    OaSysRoleMapper oaSysRoleMapper;

    @Autowired
    private DidiSysAreaMapper didiSysAreaMapper;
    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDWalletMapper oaDWalletMapper;

    @Autowired
    private OaDWalletRecordMapper oaDWalletRecordMapper;

    @Autowired
    private  OaServiceOrderOperationRecordMapper oaServiceOrderOperationRecordMapper;

    @Autowired
    private OaSysUserMapper oaSysUserMapper;


    /**
     * 取消订单
     *
     * @param worksheetCancelOrderParam
     * @return
     */
    @Override
    public DiDiRv cancelOrder(WorksheetCancelOrderParam worksheetCancelOrderParam) {
        //获取订单信息
        String orderId = worksheetCancelOrderParam.getOrderId();
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            log.info("未获取到订单信息，订单号:{}", orderId);
            throw PangException.create(EErrorCode.unOrderNo);
        }

        if (EOrderStatus.reservationLocation.getType().equals(oaCOrderPersonal.getOrderStatus())//4司机前往预约地点
                || EOrderStatus.driverArrived.getType().equals(oaCOrderPersonal.getOrderStatus())) {//5司机已到达
            Date date=new Date();
            Long sysUserId=0L;
            String name="";
            OaServiceOrderOperationRecord record=new OaServiceOrderOperationRecord();
            record.setRecordId(IDUtil.nextId());
            record.setCreateTime(date);
            record.setUpdateTime(date);
            if(CheckUtil.strIsNotEmpty(worksheetCancelOrderParam.getWorksheetId())){
                record.setWorksheetId(worksheetCancelOrderParam.getWorksheetId());
            }
            if(CheckUtil.strIsNotEmpty(worksheetCancelOrderParam.getUserToken())){
                List<OaSysUser> oaSysUserList=getOaSysUser(worksheetCancelOrderParam.getUserToken());
                if(!oaSysUserList.isEmpty()){
                    name=oaSysUserList.get(0).getLoginName();
                    sysUserId=oaSysUserList.get(0).getSysUserId();
                }
            }
            record.setOperationType(EOrderOperation.cancel.getType());
            record.setOperation(name);
            record.setCreateUser(sysUserId);
            record.setUpdateUser(sysUserId);
            record.setOrderId(worksheetCancelOrderParam.getOrderId());
            oaServiceOrderOperationRecordMapper.insert(record);
            //调用滴滴服务
            CloseOrderParam closeOrderParam = new CloseOrderParam();
            closeOrderParam.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
            closeOrderParam.setOrder_id(oaCOrderPersonal.getOrderNo());
            closeOrderParam.setOrder_status(String.valueOf(EDiDiOrderStatus.serviceClose.getType()));
            DiDiRv closeResult = customerServiceOperationService.getCloseOrder(closeOrderParam);//业务逻辑在滴滴接口中处理
            return closeResult;
        } else {
            log.info(String.format("当前状态{%s}不允许取消订单!", oaCOrderPersonal.getOrderStatus()));
            return DiDiRv.wrap(EDiDiErrorCode.cancelOrderStatusError, new Object());
        }
    }


    /**
     * 关闭订单
     *
     * @param param
     * @return
     */
    @Override
    public DiDiRv getCloseOrder(WorksheetCloseOrderParam param) {
        //获取订单信息
        String orderId = param.getOrder_id();
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            log.info("未获取到订单信息，订单号:{}", orderId);
            throw PangException.create(EErrorCode.unOrderNo);
        }

        if (EOrderStatus.duringTrip.getType().equals(oaCOrderPersonal.getOrderStatus())//6行程中
                || EOrderStatus.sendBill.getType().equals(oaCOrderPersonal.getOrderStatus())//14待发起收款
                || EOrderStatus.servicceItineraryClose.getType().equals(oaCOrderPersonal.getOrderStatus())//19客服行程中关单
                || EOrderStatus.normalOrderPendingPayment.getType().equals(oaCOrderPersonal.getOrderStatus())) {//7正常订单待支付
            Date date=new Date();
            Long sysUserId=0L;
            String name="";
            OaServiceOrderOperationRecord record=new OaServiceOrderOperationRecord();
            record.setRecordId(IDUtil.nextId());
            record.setCreateTime(date);
            record.setUpdateTime(date);
            if(CheckUtil.strIsNotEmpty(param.getWorksheetId())){
                record.setWorksheetId(param.getWorksheetId());
            }
            record.setOperationType(EOrderOperation.close.getType());
            if(CheckUtil.strIsNotEmpty(param.getUser_token())){
                List<OaSysUser> oaSysUserList=getOaSysUser(param.getUser_token());
                if(!oaSysUserList.isEmpty()){
                    name=oaSysUserList.get(0).getLoginName();
                    sysUserId=oaSysUserList.get(0).getSysUserId();
                }
            }
            record.setOperation(name);
            record.setCreateUser(sysUserId);
            record.setUpdateUser(sysUserId);
            record.setOrderId(orderId);
            oaServiceOrderOperationRecordMapper.insert(record);
            //调用滴滴服务
            CloseOrderParam closeOrderParam = new CloseOrderParam();
            closeOrderParam.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
            closeOrderParam.setOrder_id(oaCOrderPersonal.getOrderNo());
            closeOrderParam.setOrder_status(String.valueOf(EDiDiOrderStatus.serviceClose.getType()));
            closeOrderParam.setPassenger_bill(param.getPassenger_bill());
            DiDiRv closeResult = customerServiceOperationService.getCloseOrder(closeOrderParam);
            return closeResult;
        }else{
            log.info(String.format("当前状态{%s}不允许关闭订单!", oaCOrderPersonal.getOrderStatus()));
            return DiDiRv.wrap(EDiDiErrorCode.closeOrderStatusError, new Object());
        }
    }

    /**
     * 订单改价接口
     *
     * @param param
     * @return
     */
    @Override
    public DiDiRv getChangePrice(ChangePriceParam param) {
        String order_id = param.getOrder_id();
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, order_id));
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            log.error("未获取到该订单信息! order_id : {}", order_id);
            return DiDiRv.wrap(EDiDiErrorCode.notQueryOrderInfo, new Object());
        }

        if (EOrderStatus.normalOrderPendingPayment.getType().equals(oaCOrderPersonal.getOrderStatus())) { //7正常订单待支付
            PassengerBill passenger_bill = param.getPassenger_bill();
            if (CheckUtil.objIsEmpty(passenger_bill)) {
                log.error("请确认账单信息! passenger_bill : {}", passenger_bill.toString());
                return DiDiRv.wrap(EDiDiErrorCode.inspectionAmount, new Object());
            }

            passenger_bill = testParameter(passenger_bill, oaCOrderPersonal, EUpdateOrderType.changePrice);
            if (CheckUtil.objIsEmpty(passenger_bill)) {
                return DiDiRv.wrap(EDiDiErrorCode.inspectionAmount, new Object());
            }
            //无金额修改
            BigDecimal totalFee = passenger_bill.getTotal_fee();
            if (totalFee.doubleValue() == oaCOrderPersonal.getTotalFee().doubleValue()) {
                return DiDiRv.wrap(EDiDiErrorCode.inspectionAmount, new Object());
            }
            Long sysUserId=0L;
            Date date=new Date();
            OaServiceOrderOperationRecord record=new OaServiceOrderOperationRecord();
            record.setRecordId(IDUtil.nextId());
            record.setCreateTime(date);
            record.setUpdateTime(date);
            record.setOperationType(EOrderOperation.change.getType());
            if(CheckUtil.strIsNotEmpty(param.getOperator_name())){
                record.setOperation(param.getOperator_name());
                QueryWrapper<OaSysUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(OaSysUser.NAME, param.getOperator_name());
                List<OaSysUser> oaSysUserList = oaSysUserMapper.selectList(queryWrapper);
                if(!oaSysUserList.isEmpty()){
                    sysUserId=oaSysUserList.get(0).getSysUserId();
                }
            }else{
                if(CheckUtil.strIsNotEmpty(param.getUserToken())){
                    List<OaSysUser> oaSysUserList=getOaSysUser(param.getUserToken());
                    if(!oaSysUserList.isEmpty()){
                        record.setOperation(oaSysUserList.get(0).getLoginName());
                        sysUserId=oaSysUserList.get(0).getSysUserId();
                    }
                }
            }
            if(CheckUtil.strIsNotEmpty(param.getWorksheetId())){
                record.setWorksheetId(param.getWorksheetId());
            }
            if(CheckUtil.objIsNotEmpty(param.getIs_affect_account()) && param.getIs_affect_account()==1){
                record.setBearer(EDriverComingUserType.driver.getDesc());
            }else{
                record.setBearer(MessageConstant.PLATFORM);
            }
            record.setCreateUser(sysUserId);
            record.setUpdateUser(sysUserId);
            record.setOrderId(order_id);
            oaServiceOrderOperationRecordMapper.insert(record);
            passenger_bill.setTotal_fee(totalFee);
            //设置改价对象
            param.setPassenger_bill(passenger_bill);
            param.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
            param.setOrder_id(oaCOrderPersonal.getOrderNo());
            //现在测试使用所以只能如此
            //param.setOperator_name(TokenUtil.getTokenUser().getUsername());
            param.setOperator_name("system");
            ////调用滴滴服务
            return customerServiceOperationService.getChangePrice(param);
        } else {
            log.info(String.format("当前状态{%s}不允许改价!", oaCOrderPersonal.getOrderStatus()));
            return DiDiRv.wrap(EDiDiErrorCode.closeOrderStatusError, new Object());
        }
    }

    public BigDecimal inspectionAmount(BigDecimal originalValue, BigDecimal diffValue, EUpdateOrderType orderType) {
        //退款 金额必须小于总金额大于0
        if (EUpdateOrderType.refund.getType().equals(orderType.getType())) {
            if (MathUtil.compareTo(originalValue, diffValue) == false) {
                return null;
            }
            //获取退款差值
            return originalValue.subtract(diffValue);
        }

        if (EUpdateOrderType.changePrice.getType().equals(orderType.getType())) {
            if (diffValue.doubleValue() < 0) {
                return null;
            }
            return diffValue;
        }
        return null;
    }

    /**
     * 退款接口
     *
     * @param worksheetGetBillRefundParam
     * @return
     */
    @Override
    public DiDiRv getBillRefund(WorksheetGetBillRefundParam worksheetGetBillRefundParam) {
        //验证订单是否合法
        String orderId = worksheetGetBillRefundParam.getOrder_id();
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            log.info("未获取到订单信息，订单号:{}", orderId);
            throw PangException.create(EErrorCode.unOrderNo);
        }
        PassengerBill passenger_bill = worksheetGetBillRefundParam.getPassenger_bill();
        if (CheckUtil.objIsEmpty(passenger_bill)) {
            log.error("请确认账单信息! passenger_bill : {}", passenger_bill.toString());
        }
        if (EOrderStatus.paymented.getType().equals(oaCOrderPersonal.getOrderStatus())) {//12已支付
            passenger_bill = testParameter(passenger_bill, oaCOrderPersonal, EUpdateOrderType.refund);
            if (CheckUtil.objIsEmpty(passenger_bill)) {
                return DiDiRv.wrap(EDiDiErrorCode.inspectionAmount, new Object());
            }
//            passenger_bill.setTotal_fee(totalFee);
            //调用滴滴
            BigDecimal totalFee = passenger_bill.getTotal_fee();
            BillRefundParam billRefundParam = new BillRefundParam();
            billRefundParam.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
            billRefundParam.setOrder_id(oaCOrderPersonal.getOrderNo());
            billRefundParam.setLock_invoice(worksheetGetBillRefundParam.getLock_invoice());
            billRefundParam.setDetail_content(worksheetGetBillRefundParam.getDetail_content());
            //转换为分,转发给DIDI
            totalFee = totalFee.multiply(new BigDecimal(10)).multiply(new BigDecimal(10)).setScale(0);
            billRefundParam.setRefund_cost(totalFee.toString());
            billRefundParam.setOperator_name("system");
            billRefundParam.setIs_affect_account(worksheetGetBillRefundParam.getIs_affect_account());
            billRefundParam.setPassenger_bill(passenger_bill);
            DiDiRv closeResult = customerServiceOperationService.getBillRefund(billRefundParam);
            if(CheckUtil.objIsNotEmpty(closeResult)) {
                if(CheckUtil.objIsNotEmpty(closeResult.getErrno())&& closeResult.getErrno() == 0){
                    Long sysUserId=0L;
                    Date date=new Date();
                    String name="";
                    OaServiceOrderOperationRecord record=new OaServiceOrderOperationRecord();
                    record.setRecordId(IDUtil.nextId());
                    record.setCreateTime(date);
                    record.setUpdateTime(date);
                    if(CheckUtil.strIsNotEmpty(worksheetGetBillRefundParam.getWorksheetId())){
                        record.setWorksheetId(worksheetGetBillRefundParam.getWorksheetId());
                    }
                    record.setOperationType(EOrderOperation.refund.getType());
                    if(CheckUtil.strIsNotEmpty(worksheetGetBillRefundParam.getUser_token())){
                        List<OaSysUser> oaSysUserList=getOaSysUser(worksheetGetBillRefundParam.getUser_token());
                        if(!oaSysUserList.isEmpty()){
                            sysUserId=oaSysUserList.get(0).getSysUserId();
                            name=oaSysUserList.get(0).getLoginName();
                        }
                    }
                    record.setOperation(name);
                    if(CheckUtil.strIsNotEmpty(worksheetGetBillRefundParam.getIs_affect_account()) && worksheetGetBillRefundParam.getIs_affect_account().equals(ParameterEnum.ONE.getTypeName())){
                        record.setBearer(EDriverComingUserType.driver.getDesc());
                    }else{
                        record.setBearer(MessageConstant.PLATFORM);
                    }
                    record.setCreateUser(sysUserId);
                    record.setUpdateUser(sysUserId);
                    record.setOrderId(orderId);
                    oaServiceOrderOperationRecordMapper.insert(record);
                }
            }
            /*if(closeResult.getErrno() == 0){
                log.info("调用滴滴退款服务成功");
                //是否司机承担
                if("1".equals(worksheetGetBillRefundParam.getIs_affect_account())) {
                    PassengerBill passengerBill = passenger_bill;//获取账单
                    this.updateDriverWallet(oaCOrderPersonal.getDriverId(), passengerBill.getTotal_fee().negate(), "客服关单");//更新司机钱包和钱包记录
                }
                return closeResult;
            }
            else {
                log.info("调用滴滴退款服务失败");*/
            return closeResult;
            //}
        } else {
            log.info(String.format("当前状态{%s}不允许退款!", oaCOrderPersonal.getOrderStatus()));
            return DiDiRv.wrap(EDiDiErrorCode.closeOrderStatusError, new Object());
        }
    }

    public List<OaSysUser> getOaSysUser(String token){
        QueryWrapper<OaSysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUser.SYS_USER_TOKEN, token);
        return oaSysUserMapper.selectList(queryWrapper);
    }


    /**
     * 检验数据
     *
     * @param passenger_bill   账单数据
     * @param oaCOrderPersonal 订单数据
     * @return
     */
    public PassengerBill testParameter(PassengerBill passenger_bill, OaCOrderPersonal oaCOrderPersonal, EUpdateOrderType orderType) {
        //检验起步价
        BigDecimal totalFee = new BigDecimal(0);
        BigDecimal start_fee = passenger_bill.getStart_fee();
        start_fee = this.inspectionAmount(oaCOrderPersonal.getStartFee(), start_fee, orderType);
        if (CheckUtil.objIsEmpty(start_fee)) {
            return null;
        }
        passenger_bill.setStart_fee(start_fee);
        //检验里程费
        BigDecimal normal_fee = passenger_bill.getNormal_fee();
        normal_fee = this.inspectionAmount(oaCOrderPersonal.getMileageFee(), normal_fee, orderType);
        if (CheckUtil.objIsEmpty(normal_fee)) {
            return null;
        }
        passenger_bill.setNormal_fee(normal_fee);
        //检验时长费
        BigDecimal time_fee = passenger_bill.getTime_fee();
        time_fee = this.inspectionAmount(oaCOrderPersonal.getDurationFee(), time_fee, orderType);
        if (CheckUtil.objIsEmpty(time_fee)) {
            return null;
        }
        passenger_bill.setTime_fee(time_fee);
        //检验远途费
        BigDecimal empty_fee = passenger_bill.getEmpty_fee();
        empty_fee = this.inspectionAmount(oaCOrderPersonal.getDistanceFee(), empty_fee, orderType);
        if (CheckUtil.objIsEmpty(empty_fee)) {
            return null;
        }
        passenger_bill.setEmpty_fee(empty_fee);
        List<OaOrderOtherPrice> list = oaOrderOtherPriceMapper.selectList(Qw.create().eq(OaOrderOtherPrice.ORDER_NO, oaCOrderPersonal.getOrderNo()));
        BigDecimal park_fee = passenger_bill.getPark_fee();
        BigDecimal bridge_fee = passenger_bill.getBridge_fee();
        BigDecimal highway_fee = passenger_bill.getHighway_fee();

        totalFee = start_fee.add(normal_fee).add(time_fee).add(empty_fee);//.add(park_fee).add(bridge_fee).add(highway_fee);
        //获取其他费用,检验其他费用
        if (CheckUtil.collectionIsNotEmpty(list)) {
            for (OaOrderOtherPrice oaOrderOtherPrice : list) {
                BigDecimal costAmount = oaOrderOtherPrice.getCostAmount();
                if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                    highway_fee = this.inspectionAmount(costAmount, highway_fee, orderType);
                    if (CheckUtil.objIsEmpty(highway_fee)) {
                        return null;
                    }
                    totalFee = totalFee.add(highway_fee);
                    passenger_bill.setHighway_fee(highway_fee);
                } else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                    bridge_fee = this.inspectionAmount(costAmount, bridge_fee, orderType);
                    if (CheckUtil.objIsEmpty(bridge_fee)) {
                        return null;
                    }
                    totalFee = totalFee.add(bridge_fee);
                    passenger_bill.setBridge_fee(bridge_fee);
                } else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                    park_fee = this.inspectionAmount(costAmount, park_fee, orderType);
                    if (CheckUtil.objIsEmpty(park_fee)) {
                        return null;
                    }
                    totalFee = totalFee.add(park_fee);
                    passenger_bill.setPark_fee(park_fee);
                }
            }
        }
        passenger_bill.setTotal_fee(totalFee);
        return passenger_bill;
    }

    /**
     * 免单接口
     *
     * @param worksheetFreeChargeParam
     * @return
     */
    @Override
    public DiDiRv getFreeCharge(WorksheetFreeChargeParam worksheetFreeChargeParam) {
        //验证订单是否合法
        String orderId = worksheetFreeChargeParam.getOrderId();
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            log.info("未获取到订单信息，订单号:{}", orderId);
            return DiDiRv.wrapError(EDiDiErrorCode.orderPersonalSelectFail);
        }
        String handleType = worksheetFreeChargeParam.getHandleType();
        if (CheckUtil.strIsEmpty(handleType)) {
            log.info("该订单 : {} 的处理类型参数错误: {}", orderId, handleType);
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        Date date=new Date();
        String name="";
        Long sysUserId=0L;
        OaServiceOrderOperationRecord record=new OaServiceOrderOperationRecord();
        record.setRecordId(IDUtil.nextId());
        record.setCreateTime(date);
        record.setUpdateTime(date);
        record.setOperationType(EOrderOperation.freeCharge.getType());
        if(CheckUtil.strIsNotEmpty(worksheetFreeChargeParam.getUserToken())){
            List<OaSysUser> oaSysUserList=getOaSysUser(worksheetFreeChargeParam.getUserToken());
            if(!oaSysUserList.isEmpty()){
                sysUserId=oaSysUserList.get(0).getSysUserId();
                name=oaSysUserList.get(0).getLoginName();
            }
        }
        record.setOperation(name);
        if(handleType.equals(ParameterEnum.TWO.getTypeName())){
            record.setBearer(EDriverComingUserType.driver.getDesc());
        }else{
            record.setBearer(MessageConstant.PLATFORM);
        }
        if(CheckUtil.strIsNotEmpty(worksheetFreeChargeParam.getWorksheetId())){
            record.setWorksheetId(worksheetFreeChargeParam.getWorksheetId());
        }
        record.setCreateUser(sysUserId);
        record.setUpdateUser(sysUserId);
        record.setOrderId(orderId);
        oaServiceOrderOperationRecordMapper.insert(record);

        //调用滴滴
        FreeChargeParam freeChargeParam = new FreeChargeParam();
        freeChargeParam.setDetail_content(worksheetFreeChargeParam.getFreeReason());
        freeChargeParam.setOrder_id(oaCOrderPersonal.getOrderNo());
        freeChargeParam.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
        freeChargeParam.setHandleType(handleType);
        return customerServiceOperationService.getFreeCharge(freeChargeParam);
    }

    /**
     * 合力发起更新工单状态
     *
     * @param worksheetUpdateWorksheetParam
     * @return
     */
    @Override
    public WorksheetRv updateWorksheet(WorksheetUpdateWorksheetParam worksheetUpdateWorksheetParam) {
        // 传参数检查
        if (StringUtils.isBlank(worksheetUpdateWorksheetParam.getWorksheetId())) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        UpdateWorkParam updateWorkParam = this.convertUpdateParam(worksheetUpdateWorksheetParam);

        // 获取工单信息
        OaSysWorksheet worksheet = iOaSysWorksheetService.queryWorksheetByHeliWorksheetId(worksheetUpdateWorksheetParam.getWorksheetId());

        try {
            DiDiRv diDiRv = workService.getUpdateWork(updateWorkParam);
            if (diDiRv != null
                    && 0 == diDiRv.getErrno()) {
                return WorksheetRv.wrapSuccess();
            } else {
                return WorksheetRv.wrapErrorCode(WorksheetErrorCode.updateWorksheetError);
            }
        } catch (Exception ex) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.updateWorksheetError);
        }
    }

    /**
     * 查询订单详情接口
     *
     * @param param
     * @return
     */
    @Override
    public WorksheetRv getOrderPersonalDetail(WorksheetGetOrderPersonalDetailParam param) {
        if (StringUtils.isBlank(param.getOrderId())) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        // 查询订单
        OaCOrderPersonal order = iOrderPersonalService.getOrderDetail(param.getOrderId());

        if (CheckUtil.objIsEmpty(order)
                || order.getPersonalId() == null
                || order.getPersonalId() <= 0) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        OrderDetailsResult orderDetailsResult = new OrderDetailsResult();

        // 订单id
        orderDetailsResult.setOrder_id(order.getPersonalId().toString());
        //获取司机信息
        OaDUser oaDUser = oaDUserMapper.selectById(order.getDriverId());
        if (CheckUtil.objIsNotEmpty(oaDUser)) {
            orderDetailsResult.setDriver_name(oaDUser.getDriverName());
            orderDetailsResult.setDriver_id(String.valueOf(oaDUser.getDriverId()));
        }
        // 设置订单状态
        orderDetailsResult.setStatus(order.getOrderStatus() + "");
        // 实时行驶距离
        orderDetailsResult.setDriver_metre(order.getDurationTime());
        // 实时行驶时间
        orderDetailsResult.setDriver_minute(order.getMilageDistance());
        //是订单起点
        orderDetailsResult.setStart_position(order.getDriverStartAddress());
        //是下单时间
        if (order.getOrderTime() != null) {
            orderDetailsResult.setOrder_time(order.getOrderTime().toString());
        }
        List<OrderDetailListResult> priceList = new ArrayList<OrderDetailListResult>();
        OrderDetailListResult results = new OrderDetailListResult();

        // price id与order相同
        results.setPrice_id(order.getPersonalId().toString());

        // 起步价(起步价模式必传；基础费模式不传，或者为0)
        // 起步价、里程费、时长费、远途费
        results.setStart_fee(order.getStartFee());
        results.setNormal_fee(order.getMileageFee());
        results.setTime_fee(order.getDurationFee());
        results.setEmpty_fee(order.getDistanceFee());
        results.setUrgent_fee(order.getPeakAddFee());

        // 其他费用、过桥费、停车费、高速费、普通时段计费时间
        BigDecimal otherMoney = new BigDecimal(0);
        BigDecimal bridgeMoney = new BigDecimal(0);
        BigDecimal parkMoney = new BigDecimal(0);
        BigDecimal highwayMoney = new BigDecimal(0);

        // 特殊时段费、远途行驶距离、基础费、基础费补足、计价行驶距离、普通时段计费时间
        if (CheckUtil.objIsNotEmpty(order.getSpecialPeriodFee())) {
            // 如果存在特殊时段费，保存
            results.setTime_rate_fee(order.getSpecialPeriodFee());
        }
        results.setEmpty_distance(order.getEmptyDistance());
        results.setLimit_fee(order.getBaseFee());
        results.setLimit_pay(order.getBaseSupplementFee());
        //获取里程(m)
        BigDecimal milageDistance = order.getMilageDistance();
        if (CheckUtil.objIsEmpty(milageDistance)) {
            milageDistance = new BigDecimal(0);
        }
        results.setNormal_distance(BigDecimal.valueOf(milageDistance.doubleValue() * 1000));
        //获取时长(s)
        BigDecimal durationTime = order.getDurationTime();
        if (CheckUtil.objIsEmpty(durationTime)) {
            durationTime = new BigDecimal(0);
        }
        results.setNormal_time(durationTime.intValue() * 60);

        QueryWrapper<OaOrderOtherPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaOrderOtherPrice.ORDER_NO, order.getOrderNo());

        List<OaOrderOtherPrice> oaOrderOtherPrices = oaOrderOtherPriceMapper.selectList(queryWrapper);

        // 其他费用
        if (CheckUtil.objIsNotEmpty(oaOrderOtherPrices)) {
            for (OaOrderOtherPrice otherPrice : oaOrderOtherPrices) {
                if (otherPrice.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                    bridgeMoney = bridgeMoney.add(otherPrice.getCostAmount());
                }
                if (otherPrice.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                    parkMoney = parkMoney.add(otherPrice.getCostAmount());
                }
                if (otherPrice.getCostType().equals(EOrderOtherPrice.otherFee.getType())) {
                    otherMoney = otherMoney.add(otherPrice.getCostAmount());
                }
                if (otherPrice.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                    highwayMoney = highwayMoney.add(otherPrice.getCostAmount());
                }
            }
        }
        results.setHighway_fee(highwayMoney);
        results.setBridge_fee(bridgeMoney);
        results.setPark_fee(parkMoney);
        results.setOther_fee(otherMoney);
        //如果总金额大于起步价,显示总金额,如果小于起步价显示起步价
        BigDecimal totalFee = order.getTotalFee();
        BigDecimal showFee = order.getStartFee();
        if (showFee.doubleValue() < totalFee.doubleValue()) {
            showFee = totalFee;
        }
        results.setTotal_fee(showFee);
        priceList.add(results);
        orderDetailsResult.setPrice_list(priceList);
        return WorksheetRv.wrap(WorksheetErrorCode.success, orderDetailsResult);
    }

    /**
     * 根据乘客手机号获取订单列表信息
     * 或者根据司机
     *
     * @param param
     * @return
     */
    @Override
    public WorksheetRv getOrderPersonalList(WorksheetgetOrderPersonalListParam param) {
        if (StringUtils.isBlank(param.getCusPhone())) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        List<OaCOrderPersonal> orderList = new ArrayList<>();
        Integer pageTotal = 0;

        // 查询乘客订单
        if (StringUtils.equals(param.getCusType(), CustomerTypeEnum.PASSENGER.getCode())) {
            // 需要先查询乘客ID，再用ID查看订单
            OtherOpenPidParam openPidParam = new OtherOpenPidParam();
            openPidParam.setPassenger_phone(param.getCusPhone());
            DiDiRv openPid = customerServiceOperationService.getOpenPid(openPidParam);
            String s = JSON.toJSONString(openPid.getData());
            OtherOpenPidResults openPidResults = JSONObject.parseObject(s, OtherOpenPidResults.class);
            param.setDidUserId(openPidResults.getOpen_pid());
            orderList = iOrderPersonalService.getOrderDetailList(param);
            pageTotal = iOrderPersonalService.selectListLimitTotal(param);
        }

        // 查询司机订单
        if (StringUtils.equals(param.getCusType(), CustomerTypeEnum.DRIVER.getCode())) {
            // 查询乘客订单
            orderList = iOrderPersonalService.getDriverOrderDetailList(param);
            pageTotal = iOrderPersonalService.selectDriverListLimitTotal(param);
        }

        // 检测数据是否存在
        if (orderList == null
                || orderList.size() <= 0) {
            return WorksheetRv.wrapErrorCodeArray(WorksheetErrorCode.orderPersonalSelectFail);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<OrderDetailsResult> orderDetailsListResult = new ArrayList<OrderDetailsResult>();
        for (OaCOrderPersonal order : orderList) {


            if (CheckUtil.objIsEmpty(order)) {
                continue;
            }
            OrderDetailsResult orderDetailResult = new OrderDetailsResult();
            // 设置司机信息
            orderDetailResult.setDriver_id(order.getDriverId().toString());
            orderDetailResult.setDriver_name(order.getDriverName());

            // 设置订单状态
            orderDetailResult.setStatus(order.getOrderStatus() + "");
            // 实时行驶距离
            orderDetailResult.setDriver_metre(order.getDurationTime());
            // 实时行驶时间
            orderDetailResult.setDriver_minute(order.getMilageDistance());

            orderDetailResult.setOrder_id(order.getOrderNo());
            orderDetailResult.setOrder_time(simpleDateFormat.format(order.getCreateTime()));
            orderDetailResult.setStart_position(order.getStartAddress());

            List<OrderDetailListResult> priceList = new ArrayList<OrderDetailListResult>();
            OrderDetailListResult results = new OrderDetailListResult();

            // 起步价(起步价模式必传；基础费模式不传，或者为0)
            // 起步价、里程费、时长费、远途费
            results.setStart_fee(order.getStartFee());
            results.setNormal_fee(order.getMileageFee());
            results.setTime_fee(order.getDurationFee());
            results.setEmpty_fee(order.getDistanceFee());
            results.setUrgent_fee(order.getPeakAddFee());

            // 其他费用、过桥费、停车费、高速费、普通时段计费时间
            BigDecimal otherMoney = new BigDecimal(0);
            BigDecimal bridgeMoney = new BigDecimal(0);
            BigDecimal parkMoney = new BigDecimal(0);
            BigDecimal highwayMoney = new BigDecimal(0);

            // 特殊时段费、远途行驶距离、基础费、基础费补足、计价行驶距离、普通时段计费时间
            if (CheckUtil.objIsNotEmpty(order.getSpecialPeriodFee())) {
                // 如果存在特殊时段费，保存
                results.setTime_rate_fee(order.getSpecialPeriodFee());
            }
            results.setEmpty_distance(order.getEmptyDistance());
            results.setLimit_fee(order.getBaseFee());
            results.setLimit_pay(order.getBaseSupplementFee());
            //获取里程(m)
            BigDecimal milageDistance = order.getMilageDistance();
            if (CheckUtil.objIsEmpty(milageDistance)) {
                milageDistance = new BigDecimal(0);
            }
            results.setNormal_distance(BigDecimal.valueOf(milageDistance.doubleValue() * 1000));
            //获取时长(s)
            BigDecimal durationTime = order.getDurationTime();
            if (CheckUtil.objIsEmpty(durationTime)) {
                durationTime = new BigDecimal(0);
            }
            results.setNormal_time(durationTime.intValue() * 60);

            QueryWrapper<OaOrderOtherPrice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OaOrderOtherPrice.ORDER_NO, order.getOrderNo());

            List<OaOrderOtherPrice> oaOrderOtherPrices = oaOrderOtherPriceMapper.selectList(queryWrapper);

            // 其他费用
            if (CheckUtil.objIsNotEmpty(oaOrderOtherPrices)) {
                for (OaOrderOtherPrice otherPrice : oaOrderOtherPrices) {
                    if (otherPrice.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                        bridgeMoney = bridgeMoney.add(otherPrice.getCostAmount());
                    }
                    if (otherPrice.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                        parkMoney = parkMoney.add(otherPrice.getCostAmount());
                    }
                    if (otherPrice.getCostType().equals(EOrderOtherPrice.otherFee.getType())) {
                        otherMoney = otherMoney.add(otherPrice.getCostAmount());
                    }
                    if (otherPrice.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                        highwayMoney = highwayMoney.add(otherPrice.getCostAmount());
                    }
                }
            }
            results.setHighway_fee(highwayMoney);
            results.setBridge_fee(bridgeMoney);
            results.setPark_fee(parkMoney);
            results.setOther_fee(otherMoney);
            //如果总金额大于起步价,显示总金额,如果小于起步价显示起步价
            BigDecimal totalFee = order.getTotalFee();
            BigDecimal showFee = order.getStartFee();
            if (showFee.doubleValue() < totalFee.doubleValue()) {
                showFee = totalFee;
            }
            results.setTotal_fee(showFee);
            priceList.add(results);

            orderDetailResult.setPrice_list(priceList);

            orderDetailsListResult.add(orderDetailResult);
        }

        return WorksheetRv.wrapHeliGetOrderDetail(WorksheetErrorCode.success, orderDetailsListResult, pageTotal);
    }

    /**
     * 司机处罚
     *
     * @param worksheetetDriverPenaltyDetailParam
     * @return
     */
    @Override
    public WorksheetRv setDriverPenaltyDetail(WorksheetetDriverPenaltyDetailParam worksheetetDriverPenaltyDetailParam) {
        try {
            OaSysWorksheet oaSysWorksheet = iOaSysWorksheetService.queryWorksheetByHeliWorksheetId(worksheetetDriverPenaltyDetailParam.getWorksheetId());

            if (oaSysWorksheet == null) {
                return WorksheetRv.wrapErrorCode(WorksheetErrorCode.getWorksheetFailed);
            } else {

                List<OaDUserPenaltyParam> oaDUserPenaltyParamList = this.createDriverPenaltyList(oaSysWorksheet, worksheetetDriverPenaltyDetailParam);
                if (oaDUserPenaltyParamList == null
                        || oaDUserPenaltyParamList.size() <= 0) {
                    return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
                }

                iOaDUserPenaltyService.insertoaDUserPenalty(oaDUserPenaltyParamList);

                return WorksheetRv.wrapSuccess();
            }
        } catch (Exception ex) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.driverPenaltyFailed);
        }
    }

    /**
     * 司机信息接口
     *
     * @param param
     * @return
     */
    @Override
    public WorksheetRv getDriverDetail(WorksheetetGetDriverDetailParam param) {
        //参数判断
        if (StringUtils.isBlank(param.getDriverPhone())) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        DriverDetailResult driverDetailResult = userInfoMapper.selectDriverDetail(param.getDriverPhone());

        if (driverDetailResult != null) {
            return WorksheetRv.wrap(WorksheetErrorCode.success, driverDetailResult);
        } else {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.noDriverError);
        }
    }

    /**
     * 根据合力提供信息创建创建工单
     *
     * @param fromHeliWorksheetParam 合力工单信息
     * @return
     */
    @Override
    public WorksheetRv createWorksheet(FromHeliWorksheetParam fromHeliWorksheetParam) {
        // 创建系统工单
        OaSysWorksheet oaSysWorksheet = null;
        // 调用didi创建工单接口
        CreateWorkParam createWorkParam = null;

        try {
            // 获取合力工单信息
            oaSysWorksheet = this.convertCreateWorksheetInfo(fromHeliWorksheetParam);
            // 初始化didi工单信息
            this.addDidiWorksheetInfo(oaSysWorksheet, fromHeliWorksheetParam);
            // 创建didi创建工单信息
            createWorkParam = this.convertCreateDiDiWorksheetDidi(oaSysWorksheet);
        } catch (Exception ex) {
            log.error("工单数据错误");
            throw new WorksheetException(WorksheetErrorCode.worksheetDataError);
        }

        try {
            iOaSysWorksheetService.insertOaSysWorksheet(oaSysWorksheet);
        } catch (Exception ex) {
            log.error("创建系统工单失败");
            throw new WorksheetException(WorksheetErrorCode.createWorksheetError);
        }

        DiDiRv worksheet = null;

        try {
            // 调用滴滴新建工单
            worksheet = workService.getCreateWork(createWorkParam);

            if (worksheet != null && 0 == worksheet.getErrno()) {
                // 成功返回滴滴工单id
                log.error("创建didi工单成功");
                Object dataObject = worksheet.getData();
                String dataStr = JSON.toJSONString(dataObject);
                CreateWorkResult createWorkResult = JSONObject.parseObject(dataStr, CreateWorkResult.class);

                oaSysWorksheet.setDidiWorksheetId(createWorkResult.getWorksheet_id());
            } else {
                log.error("创建didi工单失败");
                return WorksheetRv.wrapErrorCode(WorksheetErrorCode.createWorksheetError);
            }
        } catch (Exception ex) {
            log.error("创建didi工单失败");
            throw new WorksheetException(WorksheetErrorCode.createWorksheetError);
        }
        // 访问滴滴成功，更新数据
        iOaSysWorksheetService.updateDiDiWorkSheetId(oaSysWorksheet);

        return WorksheetRv.wrapSuccess(new Object());
    }

    /**
     * 获取城市CODE
     *
     * @param cityId
     * @return
     */
    public List<OaSysArea> getCityCode(String cityId) {
        QueryWrapper<DidiSysArea> diAreaQueryWrapper = new QueryWrapper<>();
        diAreaQueryWrapper.eq(DidiSysArea.CITY_CODE, cityId);
        List<DidiSysArea> diAreaList = didiSysAreaMapper.selectList(diAreaQueryWrapper);
        List<OaSysArea> areaList = new ArrayList<>();
        if (!diAreaList.isEmpty()) {
            QueryWrapper<OaSysArea> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.like(OaSysArea.NAME, diAreaList.get(0).getName());
            // 查询type为3的市，否则容易出现混乱
            areaQueryWrapper.eq(OaSysArea.TYPE, ParameterEnum.THREE.getType());
            areaList = oaSysAreaMapper.selectList(areaQueryWrapper);
        }
        return areaList;
    }

    /**
     * 解除司机锁定
     *
     * @param driverId
     * @return
     */
    public Boolean driverUnlock(String driverId) {
        UpdateWrapper<OaDUserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(OaDUserInfo.IS_ORDER, 0);
        updateWrapper.eq(OaDUserInfo.DRIVER_ID, driverId);
        try {
            return iUserInfoService.update(updateWrapper);
        } catch (Exception e) {
            log.error("解除司机锁定失败");
        }
        return false;
    }

    /**
     * 创建didi创建工单参数
     *
     * @param oaSysWorksheet
     * @return
     */
    private CreateWorkParam convertCreateDiDiWorksheetDidi(OaSysWorksheet oaSysWorksheet) {
        CreateWorkParam createWorkOrderParam = new CreateWorkParam();

        /**
         * heli工单ID
         */
        createWorkOrderParam.setWorksheet_id(oaSysWorksheet.getHeliWorksheetId());

        /**
         * 工单是否需要升级 finish:一线工单, customer_service:二线工单，升级工单 temp_store: 暂存
         */
        createWorkOrderParam.setWfrole(oaSysWorksheet.getWfrole());

        /**
         * 问题分类，客服系统统一问题分类id
         */
        createWorkOrderParam.setDict_id(oaSysWorksheet.getDictId());

        /**
         * 内容
         */
        createWorkOrderParam.setContent(oaSysWorksheet.getContent());

        /**
         * 订单号
         */
        createWorkOrderParam.setOrder_id(oaSysWorksheet.getOrderNo());

        /**
         * 区号
         */
        createWorkOrderParam.setDistrict(oaSysWorksheet.getDistrict());

        return createWorkOrderParam;
    }

    /**
     * 系统工单补充滴滴信息初始化信息
     *
     * @param oaSysWorksheet
     * @param fromHeliWorksheetParam
     */
    private void addDidiWorksheetInfo(OaSysWorksheet oaSysWorksheet, FromHeliWorksheetParam fromHeliWorksheetParam) {

        // 工单是否需要升级:二线工单
        oaSysWorksheet.setWfrole("customer_service");
        // 问题分类，客服系统统一问题分类id
        oaSysWorksheet.setDictId(fromHeliWorksheetParam.getDict_id());

        //工单内容
        oaSysWorksheet.setContent(fromHeliWorksheetParam.getContent());

        //问题分类
        oaSysWorksheet.setQuestionType(fromHeliWorksheetParam.getTicketClassify());

        //电话
        oaSysWorksheet.setPhone(fromHeliWorksheetParam.getFeedbackPhone());

        //加急数值
        oaSysWorksheet.setLevel("1");
    }

    /**
     * 收集合力数据，创建系统工单参数
     *
     * @param fromHeliWorksheetParam
     * @return
     */
    private OaSysWorksheet convertCreateWorksheetInfo(FromHeliWorksheetParam fromHeliWorksheetParam) {
        OaSysWorksheet oaSysWorksheet = new OaSysWorksheet();

        // 基础工单数据
        Date date = new Date();
        OaSysUser oaSysUser = (OaSysUser) TokenUtil.getTokenUserEntityHeLi(fromHeliWorksheetParam.getUserToken(), OaSysUser.class);
        oaSysWorksheet.setCreateUser(oaSysUser.getSysUserId().toString());
        oaSysWorksheet.setCreateTime(date);

        oaSysWorksheet.setWorksheetId(IDUtil.nextId());
        // 查询城市
        List<OaSysArea> areaList = getCityCode(fromHeliWorksheetParam.getDistrict());
        if (CheckUtil.collectionIsEmpty(areaList)) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        String code = areaList.get(0).getAdCode();
        oaSysWorksheet.setCityCode(code);

        oaSysWorksheet.setOrderId(fromHeliWorksheetParam.getOrderNo());
        // 合力工单id
        oaSysWorksheet.setHeliWorksheetId(fromHeliWorksheetParam.getWorksheet_id());

        // 工单的来源 = heli
        oaSysWorksheet.setWorksheetSource(EWorksheetResource.heli.getValue());

        // 行政区号
        oaSysWorksheet.setDistrict(fromHeliWorksheetParam.getDistrict());

        // 订单编号
        oaSysWorksheet.setOrderNo(fromHeliWorksheetParam.getOrderNo());

        // 工单编号
        oaSysWorksheet.setTicketNo(fromHeliWorksheetParam.getTicketNo());

        // 反馈人
        oaSysWorksheet.setFeedbackPerson(fromHeliWorksheetParam.getFeedbackPerson());

        // 反馈方
        oaSysWorksheet.setFeedbackParty(fromHeliWorksheetParam.getFeedbackParty());

        // 反馈人联系方式
        oaSysWorksheet.setFeedbackPhone(fromHeliWorksheetParam.getFeedbackPhone());

        // 工单状态
        oaSysWorksheet.setTicketStatus(fromHeliWorksheetParam.getTicketStatus());

        // 工单类型
        oaSysWorksheet.setTicketType(fromHeliWorksheetParam.getTicketType());

        // 加急状态
        oaSysWorksheet.setUrgentStatus(fromHeliWorksheetParam.getUrgentStatus());

        // 工单来源
        oaSysWorksheet.setTicketFrom(fromHeliWorksheetParam.getTicketFrom());

        // 工单分类
        oaSysWorksheet.setTicketClassify(fromHeliWorksheetParam.getTicketClassify());

        // 创建时间
        if (fromHeliWorksheetParam.getCreateTime() != null) {
            oaSysWorksheet.setCreateTime(fromHeliWorksheetParam.getCreateTime());
        }

        // 创建人
        oaSysWorksheet.setCreateUser(fromHeliWorksheetParam.getCreateUser());

        // 处理时间
        if (fromHeliWorksheetParam.getHandleTime() != null) {
            oaSysWorksheet.setHandleTime(fromHeliWorksheetParam.getHandleTime());
        }

        // 处理人
        oaSysWorksheet.setHandler(fromHeliWorksheetParam.getHandler());

        // 处理内容
        oaSysWorksheet.setHandleContent(fromHeliWorksheetParam.getHandleContent());

        // 司机id
        oaSysWorksheet.setDriverId(fromHeliWorksheetParam.getDriverId());

        // 抄送人员
        oaSysWorksheet.setCopyPerson(fromHeliWorksheetParam.getCopyPerson());

        // 加急时间
        oaSysWorksheet.setUrgentTime(fromHeliWorksheetParam.getUrgentTime());

        return oaSysWorksheet;
    }

    /**
     * 创建请求滴滴更新工单状态参数
     *
     * @param worksheetUpdateWorksheetParam
     * @return
     */
    private UpdateWorkParam convertUpdateParam(WorksheetUpdateWorksheetParam worksheetUpdateWorksheetParam) {

        UpdateWorkParam updateWorkParam = new UpdateWorkParam();
        // 系统工单ID
        updateWorkParam.setWorksheet_id(worksheetUpdateWorksheetParam.getWorksheetId());
        // 更新事件
        updateWorkParam.setAction(worksheetUpdateWorksheetParam.getAction());
        // 更新内容
        updateWorkParam.setContent(worksheetUpdateWorksheetParam.getContent());

        updateWorkParam.setDict_id(worksheetUpdateWorksheetParam.getScene3());

        return updateWorkParam;
    }

    /**
     * 获取当前的登录用户的电话条用户信息
     *
     * @return
     */
    @Override
    public SoftPhoneUserInfoResult getSoftPhoneUserInfo() {
        Boolean hasPhoneBar = this.hasPhoneBarAuth();
        try {
            if (hasPhoneBar) {
                TokenUser tokenUser = TokenUtil.getTokenUser();
                if (tokenUser != null
                        && tokenUser.getTokenUserId() > 0) {
                    SoftPhoneUserInfoResult softPhoneUserInfoResult = userInfoMapper.getSoftPhoneUserInfo(tokenUser.getTokenUserId());
                    softPhoneUserInfoResult.setUserId(String.valueOf(tokenUser.getTokenUserId()));

                    return softPhoneUserInfoResult;
                    //获取电话条地址
                    /*HeliPhoneUrlResult heliPhoneUrlResult = getHeliPhoneUrl();
                    if (heliPhoneUrlResult != null
                            && !"".equals(heliPhoneUrlResult.getHeliPhoneUrl())) {
                        softPhoneUserInfoResult.setHeliPhoneUrl(heliPhoneUrlResult.getHeliPhoneUrl());
                        softPhoneUserInfoResult.setCompanyAccount(heliPhoneUrlResult.getCompanyAccount());

                        log.info(softPhoneUserInfoResult.getHeliPhoneUrl());
                        return softPhoneUserInfoResult;
                    } else {
                        return null;
                    }*/
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 判断当前登录人员是否有电话条权限
     *
     * @return
     */
    @Override
    public Boolean hasPhoneBarAuth() {
        try {
            TokenUser tokenUser = TokenUtil.getTokenUser();

            OaSysRole oaSysRole = this.getRole("客服人员");
            if (tokenUser != null
                    && tokenUser.getRoles() != null
                    && tokenUser.getRoles().contains(oaSysRole.getRoleId())) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 获取订单状态
     *
     * @param worksheetGetOrderPersonalStatusParam
     * @return
     */
    @Override
    public WorksheetRv getOrderPersonalStatus(WorksheetGetOrderPersonalStatusParam worksheetGetOrderPersonalStatusParam) {
        if (StringUtils.isBlank(worksheetGetOrderPersonalStatusParam.getOrderId())) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        // 查询订单
        OaCOrderPersonal order = iOrderPersonalService.getOrderDetail(worksheetGetOrderPersonalStatusParam.getOrderId());

        if (CheckUtil.objIsEmpty(order)
                || order.getPersonalId() == null
                || order.getPersonalId() <= 0) {
            return WorksheetRv.wrapErrorCode(WorksheetErrorCode.parameterError);
        }

        OrderStatusResult orderStatusResult = new OrderStatusResult();

        // 设置订单状态
        orderStatusResult.setStatus(order.getOrderStatus() + "");

        return WorksheetRv.wrap(WorksheetErrorCode.success, orderStatusResult);
    }

    /**
     * 获取名称获取权限ID
     */
    private OaSysRole getRole(String name) {
        // 查询机构角色关联
        QueryWrapper<OaSysRole> queryWrapper = new QueryWrapper<OaSysRole>();
        queryWrapper.eq(OaSysRole.NAME, name);
        List<OaSysRole> roleList = oaSysRoleMapper.selectList(queryWrapper);

        if (roleList != null
                && roleList.size() > 0) {
            return roleList.get(0);
        } else {
            throw new WorksheetException(WorksheetErrorCode.getRoleFailed);
        }
    }

    /**
     * 创建司机处罚信息
     *
     * @param oaSysWorksheet
     * @param worksheetetDriverPenaltyDetailParam
     */
    private List<OaDUserPenaltyParam> createDriverPenaltyList(OaSysWorksheet oaSysWorksheet, WorksheetetDriverPenaltyDetailParam worksheetetDriverPenaltyDetailParam) {
        String[] penaltyTypeList = worksheetetDriverPenaltyDetailParam.getDeregulationType().split(",");

        List<OaDUserPenaltyParam> oaDUserPenaltyParamList = new ArrayList<OaDUserPenaltyParam>();

        for (String penaltyType : penaltyTypeList) {
            OaDUserPenaltyParam oaDUserPenaltyParam = new OaDUserPenaltyParam();
            // 司机id
            Long driveId = Long.parseLong(worksheetetDriverPenaltyDetailParam.getDriverId());
            oaDUserPenaltyParam.setDriverId(driveId);
            //工单编号
            oaDUserPenaltyParam.setWorkOrderNumber(oaSysWorksheet.getTicketNo());
            //订单编号
            oaDUserPenaltyParam.setOrderNumber(oaSysWorksheet.getOrderNo());

            //违规类型
            String deregulationType = penaltyType;

            oaDUserPenaltyParam.setPunishmentType(deregulationType);

            oaDUserPenaltyParamList.add(oaDUserPenaltyParam);
        }

        return oaDUserPenaltyParamList;
    }

    /**
     * 客服关单
     *
     * @param oaCOrderPersonal
     */
    @Override
    public void closeOrderStatus(OaCOrderPersonal oaCOrderPersonal) {
        //成功 更新订单状态为
        oaCOrderPersonal.setOrderStatus(EOrderStatus.cancelPendingPayment.getType());//状态=8取消行程待支付
        oaCOrderPersonalMapper.updateById(oaCOrderPersonal);

        log.info(String.format("修改订单{%s}状态为{%s}", oaCOrderPersonal.getOrderNo(), EOrderStatus.serviceClose.getType()));
    }

    /**
     * 获取电话条地址
     *
     * @return
     */
    @Override
    public HeliPhoneUrlResult getHeliPhoneUrl() {
        return this.baseMapper.getHeliPhoneUrl();
    }

    /**
     * 创建账单
     *
     * @param oaCOrderPersonal
     * @param oaSysBillRules
     * @return
     */
    public PassengerBill getPassengerBill(OaCOrderPersonal oaCOrderPersonal, OaSysBillRuleGroup oaSysBillRules) {

        PassengerBill passengerBill = new PassengerBill();
        passengerBill.setStart_fee(oaCOrderPersonal.getStartFee());//起步价
        passengerBill.setNormal_fee(oaCOrderPersonal.getMileageFee());//历程费
        //passengerBill.setNormal_distance(oaCOrderPersonal.getMilageDistance());//里程数
        passengerBill.setTime_fee(oaCOrderPersonal.getDurationFee());//时长费
        passengerBill.setNormal_time(oaCOrderPersonal.getDurationTime());//行驶时长
        passengerBill.setEmpty_fee(oaCOrderPersonal.getDistanceFee());//远途费
        passengerBill.setEmpty_distance(oaCOrderPersonal.getEmptyDistance());//远途行驶距离
        passengerBill.setTime_rate_fee(oaCOrderPersonal.getSpecialPeriodFee());//特殊时段费
        passengerBill.setUrgent_fee(oaCOrderPersonal.getPeakAddFee());//高峰加价费
        //passengerBill.setBridge_fee(oaCOrderPersonal.getb);过路费
        //passengerBill.setPark_fee();停车费
        //passengerBill.setOther_fee();其他费用
        //passengerBill.setTotal_fee();预估总价格
        //passengerBill.setHighway_fee();//高速费

        //总金额
        BigDecimal totalFee = passengerBill.getStart_fee()
                .add(passengerBill.getNormal_fee())
                .add(passengerBill.getTime_fee())
                .add(passengerBill.getEmpty_fee())
                .add(passengerBill.getPark_fee())
                .add(passengerBill.getBridge_fee())
                .add(passengerBill.getHighway_fee());
        passengerBill.setTotal_fee(totalFee);

        return passengerBill;
    }

    /**
     * 更新司机钱包
     *
     * @param amount       调整金额
     * @param amountRemark 调整备注
     */
    @Override
    @Transactional
    public void updateDriverWallet(Long driverId, BigDecimal amount, String amountRemark) {
        //查询司机钱包
        OaDWallet oaDWallet = oaDWalletMapper.selectOne(Wrappers.<OaDWallet>lambdaQuery().eq(OaDWallet::getDriverId, driverId));
        if (oaDWallet != null) {
            oaDWallet.setCashBalance(oaDWallet.getCashBalance().add(amount));
            oaDWalletMapper.updateById(oaDWallet);

            //添加钱包明细表 交易流水号规则 SJZHTZ + YYYYMMdd + 十位随机数
            Date date = new Date();

            OaDWalletRecord oaDWalletRecord = new OaDWalletRecord();
            oaDWalletRecord.setRecordId(IDUtil.nextId());
            oaDWalletRecord.setDriverId(oaDWallet.getDriverId());
            oaDWalletRecord.setAmount(oaDWallet.getCashBalance());
            oaDWalletRecord.setRecordType(0);//0 = 余额收入
            oaDWalletRecord.setTransactionTime(date);
            oaDWalletRecord.setTransactionSerialNo("SJZHTZ" +
                    DateUtil.getDateDay().replaceAll("-", "") +
                    UUID.randomUUID().toString().replace("-", "").substring(0, 9));
            oaDWalletRecord.setAmountRemark(amountRemark);
            oaDWalletRecord.setTag("lhy");
            oaDWalletRecord.setCreateUser(TokenUtil.getTokenUserId());
            oaDWalletRecord.setCreateTime(date);
            oaDWalletRecord.setUpdateUser(TokenUtil.getTokenUserId());
            oaDWalletRecord.setUpdateTime(date);

            oaDWalletRecordMapper.insert(oaDWalletRecord);
        } else {
            log.info(WorksheetErrorCode.noWalletWorksheetOperateFailed.getDesc());
            throw new WorksheetException(WorksheetErrorCode.noWalletWorksheetOperateFailed);
        }
    }
}
